package com.ftp.longdistance.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author TanYongPeng
 * <p>
 *     文件预览
 * </p>
 */
public class FileViewUtils {


    /**
     * 文件预览
     * @param response
     * @param file
     */
    public static void fileView(HttpServletResponse response, File file){
        try {
            response.reset();
            File file3 = new File(file.getAbsolutePath());
            String prefix=file3.getName().substring(file3.getName().lastIndexOf(".")+1);
            response.setHeader("Content-Type", MimeUtils.getMime(prefix));
            response.setHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Disposition", "fileName=" + file3.getName());// 设置文件名
            FileInputStream inputStream = new FileInputStream(file3);
            ServletOutputStream out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[1024];
            while ((b = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
